import {SET_VOTELIST,SELECTED,ADD_VOTE} from '../types/vote';

export interface OptionsProps{
    id:number,
    text:string,
    num:number
}

export interface VoteProps{
    id:number,
    title:string,
    desc:string,
    options:OptionsProps[],
    createUser:string,
    voteusers:string[],
    createTime:string,
    selected:number,
    size:number
}

export interface StateProps{
    votelist:VoteProps[]
}

export default (state:StateProps={votelist:[]},action:any) => {
    switch (action.type) {
        case SET_VOTELIST:{
            state.votelist = [...action.list];
            return {...state}
        }
        //投票
        case SELECTED:{
            //1.投票 id 2.选项optionId   3.谁投的票  4.票数加1
            let votelist = state.votelist.map(item => {
                if(item.id == action.id){
                    if(item.selected == -1){
                        //没投
                        //找到目标投票
                        item.selected = action.optionId;
                        item.voteusers.push(action.name);
                        let options = item.options.map(v => {
                            if(v.id == action.optionId){
                                v.num++;
                            }
                            return {...v}
                        })
                        item.options = [...options];
                        item.size++;
                    }else{
                        //投
                        alert('您已投过票')
                    }
                }
                return {...item}
            })
            return {votelist:[...votelist]}
        }

        case ADD_VOTE:{
            state.votelist = [...state.votelist,action.target];
            return {...state};
        }
        default:
            return state;
    }
}